package com.the_last.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.the_last.pojo.dto.IncrementalRolePermissionDTO;
import com.the_last.pojo.dto.SysRoleDTO;
import com.the_last.pojo.dto.AssignRolePermissionDTO;
import com.the_last.pojo.po.SysRole;
import com.the_last.pojo.po.SysPermission;
import com.the_last.service.ISysRoleService;
import com.the_last.utils.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
public class SysRoleController {
    
    private final ISysRoleService roleService;
    
    /**
     * 分页获取角色列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    public Result<Page<SysRole>> getRoleList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String roleName,
            @RequestParam(required = false) String roleCode,
            @RequestParam(required = false) Integer status) {
        
        SysRoleDTO queryDTO = new SysRoleDTO();
        queryDTO.setRoleName(roleName);
        queryDTO.setRoleCode(roleCode);
        queryDTO.setStatus(status);
        
        Page<SysRole> page = new Page<>(current, size);
        return roleService.getRoleList(page, queryDTO);
    }
    
    /**
     * 获取所有有效角色（用于下拉选择）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    public Result<List<SysRole>> getAllActiveRoles() {
        return roleService.getAllActiveRoles();
    }
    
    /**
     * 获取用户角色列表（支持返回完整信息或仅ID）
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    public Result<?> getRolesByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "false") Boolean idsOnly) {
        if (idsOnly) {
            return roleService.getRoleIdsByUserId(userId);
        }
        return roleService.getRolesByUserId(userId);
    }
    
    /**
     * 根据ID获取角色详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    public Result<SysRole> getRoleById(@PathVariable Long id) {
        SysRole role = roleService.getById(id);
        if (role == null || role.getDeleted().equals(1)) {
            return Result.fail("角色不存在");
        }
        return Result.success(role);
    }
    
    /**
     * 新增角色
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('ROLE_CREATE')")
    public Result<Void> addRole(@Valid @RequestBody SysRoleDTO roleDTO) {
        SysRole role = new SysRole();
        BeanUtils.copyProperties(roleDTO, role);
        return roleService.addRole(role);
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('ROLE_UPDATE')")
    public Result<Void> updateRole(@Valid @RequestBody SysRoleDTO roleDTO) {
        if (roleDTO.getId() == null) {
            return Result.fail("角色ID不能为空");
        }
        
        SysRole role = new SysRole();
        BeanUtils.copyProperties(roleDTO, role);
        return roleService.updateRole(role);
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_DELETE')")
    public Result<Void> deleteRole(@PathVariable Long id) {
        return roleService.deleteRole(id);
    }
    
    /**
     * 获取角色的权限列表
     */
    @GetMapping("/{roleId}/permissions")
    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    public Result<List<SysPermission>> getPermissionsByRoleId(@PathVariable Long roleId) {
        return roleService.getPermissionsByRoleId(roleId);
    }
    
    /**
     * 为角色分配权限
     */
    @PostMapping("/{roleId}/permissions")
    @PreAuthorize("hasAuthority('ROLE_PERMISSION_ASSIGN')")
    public Result<Void> assignPermissionsToRole(
            @PathVariable Long roleId, 
            @RequestBody List<Long> permissionIds) {
        return roleService.assignPermissionsToRole(roleId, permissionIds);
    }
    
    /**
     * 增量分配角色权限（推荐使用）
     * 支持同时进行权限的增加和删除操作，避免全量替换
     */
    @PostMapping("/permissions-incremental")
    @PreAuthorize("hasAuthority('ROLE_PERMISSION_ASSIGN')")
    public Result<Void> incrementalAssignRolePermissions(@Valid @RequestBody IncrementalRolePermissionDTO incrementalDTO) {
        return roleService.incrementalAssignRolePermissions(incrementalDTO);
    }
    
    /**
     * 移除角色的权限
     */
    @DeleteMapping("/{roleId}/permissions")
    @PreAuthorize("hasAuthority('ROLE_PERMISSION_REMOVE')")
    public Result<Void> removePermissionsFromRole(
            @PathVariable Long roleId, 
            @RequestBody List<Long> permissionIds) {
        return roleService.removePermissionsFromRole(roleId, permissionIds);
    }
    
    /**
     * 批量更新角色状态
     */
    @PutMapping("/update-status")
    @PreAuthorize("hasAuthority('ROLE_UPDATE')")
    public Result<Void> updateRoleStatus(@RequestParam List<Long> roleIds, @RequestParam Integer status) {
        return roleService.updateRoleStatus(roleIds, status);
    }
    
}